package com.example.study.page.fragment

import android.content.res.AssetManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.BitmapRegionDecoder
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.util.LruCache
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import com.example.study.R
import com.example.study.databinding.FragmentBitmapBinding

class BitmapFragment : Fragment() {
    private lateinit var binding: FragmentBitmapBinding

    private var resumedBitmap: Bitmap? = null
    private val lruCache = object : LruCache<String, Bitmap>(20 * 1024 * 1024) {
        override fun sizeOf(key: String?, value: Bitmap?): Int {
            return value?.allocationByteCount ?: 0
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = FragmentBitmapBinding.inflate(inflater, container, false)
        return binding.root
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val bitmap =
            BitmapFactory.decodeResource(
                resources,
                R.drawable.whale,
                BitmapFactory.Options().apply {
                    inPreferredConfig = Bitmap.Config.RGB_565
                    inSampleSize = 2
                    inBitmap = resumedBitmap
                })
        lruCache.put("origin_image", bitmap)
        showRegionImage()
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun showRegionImage() {
        val input = resources.assets.open("whale.png")
        val options = BitmapFactory.Options()
        options.inPreferredConfig = Bitmap.Config.RGB_565
        options.inSampleSize = 2
        val decoder = BitmapRegionDecoder.newInstance(input)
        val bitmap = decoder?.decodeRegion(Rect(0, 0, 400, 400), options)
        lruCache.put("region_image", bitmap)
        binding.image.setImageBitmap(bitmap)
        binding.text.text = lruCache.toString()
    }


}